package com.study_security.controller;

import com.study_security.domain.LoginUser;
import com.study_security.domain.ResponseResult;
import com.study_security.dto.ProjectFormDTO;
import com.study_security.dto.ProjectOutputDTO;
import com.study_security.entity.Project;
import com.study_security.service.ProjectService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/projects")
//@PreAuthorize("hasAnyAuthority('perm_review','perm_leader','perm_member')")
public class ProjectController {
    @Autowired
    private ProjectService projectService;

    private Long getUserId(Authentication authentication) {
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        return loginUser.getUser().getId();
    }

    /**
     * 获取用户正在进行的项目
     * @param authentication
     * @return
     */
    @PreAuthorize("hasAnyAuthority('perm_leader','perm_member')")
    @GetMapping("/ongoing")
    public List<Project> getOngoingProjects(Authentication authentication) {
        Long userId = getUserId(authentication);
        return projectService.getOngoingProjects(userId);
    }

    /**
     * 获取用户已完成的项目
     * @param authentication
     * @return
     */
    @PreAuthorize("hasAnyAuthority('perm_leader','perm_member')")
    @GetMapping("/completed")
    public List<Project> getCompletedProjects(Authentication authentication) {
        Long userId = getUserId(authentication);
        return projectService.getCompletedProjects(userId);
    }

    /**
     * 获取用户所有项目表单数据，用来做图表的接口(每个用户看到自己的)
     * @param authentication
     * @return
     */
    @PreAuthorize("hasAuthority('perm_leader')")
    @GetMapping("/user")
    public List<ProjectFormDTO> getAllProjectsByUserId(Authentication authentication) {
        Long userId = getUserId(authentication);
        return projectService.getAllProjectFormDTOByUserId(userId);
    }

    /**
     * 获取所有项目表单数据,审核用来做可视化图表
     * @return
     */
    @PreAuthorize("hasAuthority('perm_review')")
    @GetMapping("/all")
    public List<ProjectFormDTO> getAllProjectsFormDTO() {
        return projectService.getAllProjectFormDTO();
    }

    /**
     * 获取所有项目
     * @return
     */
    @GetMapping
    public List<Project> getAllProjects() {
        return projectService.getAllProject();
    }

    /**
     * 搜索用户正在进行的项目
     * @param authentication
     * @param keyword
     * @return
     */
    @PreAuthorize("hasAnyAuthority('perm_leader','perm_member')")
    @GetMapping("/ongoing/search")  //serarch?keyword=Project
    public List<Project> searchOngoingProjects(
            Authentication authentication,
            @RequestParam(required = false) String keyword,
            @RequestParam(required = false) String projectType,
            @RequestParam(required = false) String importantLevel,
            @RequestParam(required = false) String sortBy) {

        Long userId = getUserId(authentication);
        return projectService.searchOngoingProjects(userId, keyword, projectType, importantLevel, sortBy);
    }


    /**
     * 搜索用户已完成的项目
     * @param authentication
     * @param keyword
     * @return
     */
    @PreAuthorize("hasAnyAuthority('perm_leader','perm_member')")
    @GetMapping("/completed/search")
    public List<Project> searchCompletedProjects(Authentication authentication, @RequestParam String keyword) {
        Long userId = getUserId(authentication);
        return projectService.searchCompletedProjects(userId, keyword);
    }

    /**
     * 添加新项目
     * @param project
     * @param authentication
     * @param headers
     * @return
     */
    @PreAuthorize("hasAuthority('perm_leader')")
    @PostMapping("/add")
    public ResponseResult addProject(@RequestBody Project project, Authentication authentication, @RequestHeader HttpHeaders headers) {
        String token = headers.getFirst(HttpHeaders.AUTHORIZATION);
        System.out.println("Received Token: " + token);
        if (projectService.projectNameExists(project.getProjectName())) {
            return new ResponseResult(400, "项目名重复，请重新输入");
        }
        Long userId = getUserId(authentication);
        project.setResponsibleId(userId);
        boolean isAdded = projectService.addProject(userId, project);
        return new ResponseResult(isAdded ? 200 : 500, isAdded ? "Project added successfully!" : "Failed to add project.");
    }


    @PreAuthorize("hasAuthority('perm_leader')")
    @GetMapping("/output")
    public ResponseResult getProjectOutputByName(@RequestParam String projectName) {
        ProjectOutputDTO projectOutputDTO = projectService.getProjectOutputByName(projectName);
        if (projectOutputDTO != null) {
            return new ResponseResult(200, "获取项目产值数据成功", projectOutputDTO);
        } else {
            return new ResponseResult(404, "项目未找到或无相关任务数据", null);
        }
    }

}
